package com.xzy.easypoi.demo.controller;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.xzy.easypoi.demo.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Controller
@RequestMapping("user")
public class UserController {

    @RequestMapping("/{id}")
    @ResponseBody
    public User view(@PathVariable("id") int id) {
        User user = new User();
        user.setId(id);
        user.setName("zhang");
        return user;
    }

    @RequestMapping("download")
    public String download(ModelMap map) {
        List<User> users = IntStream.rangeClosed(1, 10)
                .boxed()
                .map(i -> new User(i, "x" + i))
                .collect(Collectors.toList());
        ExportParams params = new ExportParams("2412312", "测试", ExcelType.XSSF);
        params.setFreezeCol(2);
        map.put(NormalExcelConstants.DATA_LIST, users); // 数据集合
        map.put(NormalExcelConstants.CLASS, User.class);//导出实体
        map.put(NormalExcelConstants.PARAMS, params);//参数
        map.put(NormalExcelConstants.FILE_NAME, "测试");//文件名称
        return NormalExcelConstants.EASYPOI_EXCEL_VIEW;//View名称
    }

    @RequestMapping("importExcel")
    @ResponseBody
    public String importExcel(@RequestParam("file") MultipartFile multipartFile) throws Exception {
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(1);
        params.setNeedSave(false);
        List<User> users = ExcelImportUtil.importExcel(multipartFile.getInputStream(), User.class, params);
        users.stream().forEach(System.out::println);
        multipartFile.getInputStream().close();
        String msg = "导入成功";
        return msg;
    }

}
